<?php

namespace app\admin\controller\area;

use think\Db;
use think\Exception;
use Throwable;
use app\common\controller\Backend;

/**
 * 地块管理
 */
class Massif extends Backend
{
    /**
     * Massif模型对象
     * @var object
     * @phpstan-var \app\admin\model\area\Massif
     */
    protected object $model;

    protected string|array $defaultSortField = 'weigh,desc';

    protected array|string $preExcludeFields = ['id', 'create_time', 'update_time'];

    protected array $withJoinTable = ['land'];

    protected string|array $quickSearchField = ['id'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\area\Massif();
    }

    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {
        // 如果是 select 则转发到 select 方法，若未重写该方法，其实还是继续执行 index
        if ($this->request->param('select')) {
            $this->select();
        }

        /**
         * 1. withJoin 不可使用 alias 方法设置表别名，别名将自动使用关联模型名称（小写下划线命名规则）
         * 2. 以下的别名设置了主表别名，同时便于拼接查询参数等
         * 3. paginate 数据集可使用链式操作 each(function($item, $key) {}) 遍历处理
         */
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $res->visible(['land' => ['name']]);

        foreach ($res as &$value){
            $value['image'] = env('domain.image_url').$value['image'];

        }

        $this->success('', [
            'list' => $res->items(),
            'total' => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }


    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */

    public function add(): void
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate();
                        if ($this->modelSceneValidate) {
                            $validate->scene('add');
                        }
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                $land = (new \app\admin\model\area\Land())->where(['id' => $data['land_id']])->find();
                if (!$land) {
                    throw new Exception('土地不存在');
                }
                (new \app\admin\model\area\Land())->where(['id' => $data['land_id']])->setInc('total_nums');
                (new \app\admin\model\area\Land())->where(['id' => $data['land_id']])->setInc('residue_nums');
                $this->model->commit();
            } catch (Exception $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }


    public function batch(): void
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate();
                        if ($this->modelSceneValidate) {
                            $validate->scene('add');
                        }
                        $validate->check($data);
                    }
                }

                if (!$data['numbers'] || !$data['start']) {
                    $this->error(__('请填写批量数据'));
                }

                $arr = [];
                for ($i = $data['start']; $i < $data['numbers'] + $data['start']; $i++) {
                    $param['name'] = $data['name'] . $i;
                    $param['land_id'] = $data['land_id'];
                    $param['image'] = $data['image'];
                    $param['price'] = $data['price'];
                    $param['weigh'] = $i;
                    $param['status'] = $data['status'] ?? 0;
                    $arr[] = $param;
                }
                $result = $this->model->saveAll($arr);

                $land = (new \app\admin\model\area\Land())->where(['id' => $data['land_id']])->find();
                if (!$land) {
                    throw new Exception('土地不存在');
                }
                (new \app\admin\model\area\Land())->where(['id' => $data['land_id']])->setInc('total_nums',$data['numbers']);
                (new \app\admin\model\area\Land())->where(['id' => $data['land_id']])->setInc('residue_nums',$data['numbers']);


                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }


    /**
     * 删除
     *
     * @param array $ids
     *
     * @throws Throwable
     */
    public function del(array $ids = []): void
    {
        if (!$this->request->isDelete() || !$ids) {
            $this->error(__('Parameter error'));
        }

        $where = [];
        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds) {
            $where[] = [$this->dataLimitField, 'in', $dataLimitAdminIds];
        }

        $pk = $this->model->getPk();
        $where[] = [$pk, 'in', $ids];

        $count = 0;
        $data = $this->model->where($where)->select();
        $this->model->startTrans();
        $landModel = (new \app\admin\model\area\Land());
        try {
            foreach ($data as $v) {
                $count += $v->delete();
                $landModel->where(['id' => $v['land_id']])->setDec('total_nums');
                $landModel->where(['id' => $v['land_id']])->setDec('residue_nums');
            }

            $this->model->commit();
        } catch (Throwable $e) {
            $this->model->rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success(__('Deleted successfully'));
        } else {
            $this->error(__('No rows were deleted'));
        }
    }
}